package lm.concurrency.pattern.twopt;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: Min.Liu
 * @Description: 两阶段终止
 * @Date: Created in 9:00 2024/6/4
 */
@Slf4j
public class InterruptWithTwoPhaseTermination {
    public static void main(String[] args) throws InterruptedException {
        InterruptWithTwoPhaseTermination tpt = new InterruptWithTwoPhaseTermination();
        tpt.start();
        Thread.sleep(3500);
        log.debug("停止监控");
        tpt.stop();
    }

    // 监控线程
    private Thread monitorThread;
    // 停止标记
    private volatile boolean stop = false;
    // 判断是否执行过 start 方法
    private boolean starting = false;

    // 启动监控线程
    public void start() {
        monitorThread = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                // 是否被打断
                if (current.isInterrupted()) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    //重新设置打断标记
                    current.interrupt();
                }
            }
        }, "monitor");
        monitorThread.start();
    }

    // 停止监控线程
    public void stop() {
        monitorThread.interrupt();
    }
}
